// src/composables/useRepos.ts
import { getMyRepoList } from '@/api/repo/repo';
import { ref } from 'vue';
import { useRouter } from 'vue-router';

interface KnowledgeRepo {
  id?: number;
  title: string;
  description: string;
  createTime?: string;
  createBy?: string | null;
}

interface ListParam {
  searchKey: string;
  pageNum?: number;
  pageSize?: number;
}

export default function useRepos() {
  const repos = ref<KnowledgeRepo[]>([]);
  const popoverVisibilities = ref<boolean[]>([]);
  const loading = ref(false);
  const hasMore = ref(true);
  const page = ref(1);
  const perPage = 10;
  const totalPages = ref<number | null>(null); // 新增属性用于存储总页数
  const router = useRouter();
  const searchKey = ref(''); // 新增属性用于存储搜索关键词

  async function fetchRepos(param: ListParam) {
    // if (loading.value || !hasMore.value) return;
    loading.value = true;
    try {
      const res = await getMyRepoList({ ...param, pageNum: param.pageNum ?? page.value , pageSize: perPage }); // 注意 pageNum 从 0 开始
      const newRepos = res.content || [];
      const meta = res;
      // 更新知识库列表
      repos.value = [...repos.value, ...newRepos];
      updatePopoverVisibilities();

      // 更新分页信息
      totalPages.value = meta.totalPages;
      hasMore.value = !meta.last && page.value < (totalPages.value || 0);

      // 如果有更多页面，则增加页码
      if (hasMore.value) {
        page.value++;
      }
    } catch (error) {
      console.error('Error fetching repos:', error);
    } finally {
      loading.value = false;
    }
  }

  function enterNote(repo: KnowledgeRepo) {
    console.log('Clicked on:', repo);
    // 假设你有一个路由来展示单个知识库的详情
    // 使用 window.open 在新标签页中打开 repoView，并携带 repoId 作为查询参数
    // const routeUrl = new URL(window.location.origin + `/#/repoView?id=${repo.id}`);
    // const routeUrl = new URL(window.location.origin + `/#/repoView/${repo.id}`);
    // window.open(routeUrl.href, '_blank');
    router.push(`/repoView/${repo.id}`);
  }

  function updatePopoverVisibilities() {
    popoverVisibilities.value = repos.value.map(() => false);
  }

  // 监听滚动事件并加载更多数据
  function handleScroll() {
    if (loading.value || !hasMore.value) return;

    const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    const clientHeight = document.documentElement.clientHeight || window.innerHeight;
    const scrollHeight = document.documentElement.scrollHeight;

    if (scrollTop + clientHeight >= scrollHeight - 50) {
      fetchRepos({ searchKey: searchKey.value });
    }
  }

  // 搜索框内容变化时重新加载数据
  function setSearchKey(newSearchKey: string) {
    searchKey.value = newSearchKey;
    page.value = 1; // 重置页码
    repos.value = []; // 清空现有数据
    debugger;
    fetchRepos({ searchKey: searchKey.value, pageNum: 1, pageSize: perPage });
  }


  // function setSearchKey(newSearchKey: string) {
  //   if (newSearchKey === searchKey.value) return; // 如果新旧搜索关键字相同，则不执行任何操作
  //   searchKey.value = newSearchKey;
  //   page.value = 1; // 重置页码
  //   repos.value = []; // 清空现有数据
  //   fetchRepos({ searchKey: searchKey.value, pageNum: 0, pageSize: perPage }); // 注意 pageNum 从 0 开始
  // }
  // 初始化时获取第一页知识库
  const initParam: ListParam = {
    searchKey: '',
    pageNum: 1, // 注意 pageNum 从 0 开始
    pageSize: perPage,
  };

  if (repos.value.length === 0) {
    fetchRepos(initParam);
  }

  // 确保在组件卸载时移除滚动事件监听器
  const cleanup = () => {
    window.removeEventListener('scroll', handleScroll);
  };

  return { 
    repos, 
    enterNote, 
    popoverVisibilities, 
    loading, 
    hasMore,
    handleScroll, // 暴露 handleScroll 方法
    cleanup,
    setSearchKey, // 暴露 setSearchKey 方法
    searchKey // 暴露 searchKey 属性
  };
}